<template>
    <div class="loginbody">
        <div class="system-title">
            <div class="title">AIOT3 超融合中枢平台</div>
            <!-- <img src="../../assets/images/login/logo.png" alt="" style="width: 90px" /> -->
            <img src="../../assets/images/logo60s.png" alt="" style="width: 100px" />
        </div>
        <div class="logindata">
            <el-form ref="form" :model="form">
                <el-tabs v-model="activeLoginType">
                    <el-tab-pane label="用户名" name="first">
                        <el-form-item prop="username">
                            <el-input v-model="form.username" clearable placeholder="请输入账号" size="small" maxlength="16">
                                <i slot="prefix" class="el-input__icon el-icon-user"></i>
                            </el-input>
                        </el-form-item>
                        <el-form-item prop="password">
                            <el-input v-model="form.password" clearable placeholder="请输入密码" show-password size="small" maxlength="16">
                                <i slot="prefix" class="el-input__icon el-icon-lock"></i
                            ></el-input>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="手机号" name="second">
                        <el-form-item prop="phone">
                            <el-input v-model="form.phone" clearable placeholder="请输入账号" size="small" maxlength="16">
                                <i slot="prefix" class="el-input__icon el-icon-user"></i>
                            </el-input>
                        </el-form-item>
                        <el-form-item prop="password">
                            <el-input v-model="form.password" clearable placeholder="请输入密码" show-password size="small" maxlength="16">
                                <i slot="prefix" class="el-input__icon el-icon-lock"></i
                            ></el-input>
                        </el-form-item>
                    </el-tab-pane>
                </el-tabs>
            </el-form>
            <div class="UKEY">
                <el-link type="primary" style="font-size: 10px">UKEY验证</el-link>
            </div>
            <div>
                <el-checkbox v-model="agree">
                    <el-link type="primary" style="color: black; font-size: 10px">我已阅读并同意(用户注册协议)</el-link>
                </el-checkbox>
            </div>
            <div class="butt">
                <el-button type="primary" @click.native.prevent="login()" style="width: 100%">登 录</el-button>
                <el-divider><span class="divider">其他方式</span></el-divider>
                <div class="other">
                    <img src="../../assets/images/login/wxLogin.png" alt="" @click="handleOpenWxLogin" />
                </div>
            </div>
        </div>

        <el-dialog title="微信登录/注册" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
            <div class="qrcode-container">
                <img src="../../assets/images/login/wx.png" alt="" />
                <!-- <canvas ref="qrcodeCanvas"></canvas> -->
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="handOpenWxLogin()">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog title="请向右滑动进行认证" :visible.sync="dialogVisibleRz" width="30%" :before-close="handleCloseRz">
            <slide-verify
                :l="42"
                :r="10"
                :w="310"
                :h="155"
                slider-text="向右滑动"
                :imgs="imgs"
                @success="onSuccess"
                @fail="onFail"
                @refresh="onRefresh"
            ></slide-verify>
            <div>{{ msg }}</div>
        </el-dialog>
    </div>
</template>

<script>
import photo1 from '@/assets/images/rzPhoto/1.png'
import photo2 from '@/assets/images/rzPhoto/2.png'
import photo3 from '@/assets/images/rzPhoto/3.png'
import photo4 from '@/assets/images/rzPhoto/4.png'
import photo5 from '@/assets/images/rzPhoto/5.png'
import photo6 from '@/assets/images/rzPhoto/6.png'
import photo7 from '@/assets/images/rzPhoto/7.png'
import photo8 from '@/assets/images/rzPhoto/8.png'
import {AjaxCommon} from '@/libs/apiCommon.js'
import {PopupCommon} from '@/libs/popupCommon'
import {Utility} from '@/libs/utility'
import QRCode from 'qrcode'
export default {
    name: 'userLogin',
    data() {
        return {
            imgs: [photo1, photo2, photo3, photo4, photo5, photo6, photo7, photo8],
            msg: '',
            dialogVisible: false,
            dialogVisibleRz: false,
            activeLoginType: 'first',
            form: {
                password: 'blogadmin',
                username: 'blogadmin',
                phone: '15674498731'
            },
            UKEYChecked: false,
            agree: false,
            rules: {
                username: [
                    {required: true, message: '请输入用户名', trigger: 'blur'},
                    {max: 16, message: '不能大于16个字符', trigger: 'blur'}
                ],
                password: [
                    {required: true, message: '请输入密码', trigger: 'blur'},
                    {max: 16, message: '不能大于16个字符', trigger: 'blur'}
                ]
            }
        }
    },
    mounted() {
        if (localStorage.getItem('news')) {
            this.UKEYChecked = true
        }
        if (localStorage.getItem('userInfo')) {
            const userInfo = JSON.parse(localStorage.getItem('userInfo'))
            this.form.username = userInfo.username
        }

        this.setPosition()
        /*窗口自适应，关键代码*/
        window.onresize = () => {
            this.setPosition()
        }
        // this.getDiffTime()
        let _this = this
        document.onkeydown = function (e) {
            var key = window.event.keyCode
            if (key === 13) {
                //that.enterKeyup() // 触发事件
                _this.login()
            }
            console.log(e)
        }
    },
    methods: {
        onSuccess() {
            this.msg = ''
            let self = this
            AjaxCommon('/api/Auth/Login/Password', 'post', {
                USER_PASSWORD: this.form.password,
                USER_NAME: this.form.username
            })
                .then((res) => {
                    console.log(res, 'res.......')
                    if (res.data.result) {
                        // 调用token接口 api/Login/Token?name=blogadmin&pass=blogadmin
                        AjaxCommon(`/api/Login/JWTToken3.0?name=${this.form.username}&pass=${this.form.password}`, 'get', null).then(
                            (result) => {
                                if (result.data.status == 200) {
                                    var token = result.data.response.token
                                    var bear = result.data.response.token_type
                                    AjaxCommon(`/api/User/GetInfoByToken?token=${token}`, 'get', null).then((userItem) => {
                                        console.log(userItem, 'userItem.......')
                                        var userId = userItem.data.response.uID
                                        var userInfo = {
                                            id: userId,
                                            username: self.form.username,
                                            realname: userItem.data.response.uRealName,
                                            avatar: 'https://static.jeecg.com/temp/国炬软件logo_1606575029126.png',
                                            token: bear + ' ' + token
                                        }
                                        localStorage.setItem('userInfo', JSON.stringify(userInfo))
                                        localStorage.setItem('token', userInfo.token)
                                        sessionStorage.setItem('ALLMENULIST', '')
                                        sessionStorage.setItem('menuInfo', '')
                                        self.$router.push({
                                            name: 'mcIndex'
                                        })
                                    })
                                    PopupCommon.notify('success', '登录成功')
                                } else {
                                    PopupCommon.notify('error', '获取token失败')
                                }
                                console.log(result, self)
                            }
                        )
                    } else {
                        PopupCommon.notify('error', '用户名或密码错误')
                    }
                })
                .catch((err) => {
                    PopupCommon.notify('error', err.message)
                })

            // var userId = "1111"
            // var userInfo = {
            //     id: userId,
            //     username: "admin",
            //     realname: "admin",
            //     avatar: "https://static.jeecg.com/temp/国炬软件logo_1606575029126.png",
            //     token: "1111"
            // }
            // localStorage.setItem("userInfo", JSON.stringify(userInfo))
            // localStorage.setItem("token", userInfo.token)
            // sessionStorage.setItem("ALLMENULIST", "")
            // sessionStorage.setItem("menuInfo", "")
            // self.$router.push({
            //     // name: "mcIndex",
            //     name: "indexMain"
            // })
        },
        onFail() {
            this.msg = '认证失败，请重试'
        },
        onRefresh() {
            this.msg = ''
        },
        // 不管屏幕如何缩放，总保持1280的分辨率
        setPosition() {
            try {
                // 顶部菜单
                var globeHeader = document.getElementsByClassName('loginbody')
                globeHeader[0]['style']['zoom'] = window.innerWidth / 1280
            } catch (error) {
                console.log(error, 'setPosition......')
            }
        },
        async login() {
            if (!this.agree) {
                PopupCommon.notify('warning', '请勾选我已阅读并同意(用户注册协议)')
                return
            }
            if (Utility.trimEmpty(this.form.username, true) == '') {
                PopupCommon.notify('info', '请填写用户名')
                return
            }
            if (Utility.trimEmpty(this.form.password, true) == '') {
                PopupCommon.notify('info', '请填写密码')
                return
            }
            this.dialogVisibleRz = true
        },
        handleClose() {},
        handleCloseRz() {
            this.dialogVisibleRz = false
        },
        // web微信登录
        handOpenWxLogin() {
            this.dialogVisible = false
            const url =
                'https://open.weixin.qq.com/connect/qrconnect?appid=你的APPID&redirect_uri=你的回调地址&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect'

            QRCode.toCanvas(this.$refs.qrcodeCanvas, url, (error) => {
                if (error) console.error(error)
                console.log('二维码已生成')
            })
        },
        // 打开微信登录
        handleOpenWxLogin() {
            this.dialogVisible = true
        },
        remenber(data) {
            this.UKEYChecked = data
            if (this.UKEYChecked) {
                localStorage.setItem('news', JSON.stringify(this.form))
            } else {
                localStorage.removeItem('news')
            }
        }
    }
}
</script>

<style scoped lang="scss">
.loginbody {
    width: 100%;
    height: 100%;
    position: relative;
    background-image: url('../../assets/images/login/login.gif');
    background-size: 100% 100%; /* 拉伸至全屏 */
    background-repeat: no-repeat; /* 不重复 */
    .system-title {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20px;
        .title {
            color: #233f66;
            font-size: 28px;
            font-weight: 700;
            margin-left: 40px;
            transform: skewX(10deg);
            font-style: italic; /* 可选：加上斜体效果 */
        }
    }
    .logindata {
        position: absolute;
        top: 0;
        bottom: 0;
        right: 140px;
        margin: auto;
        height: 288px;
        width: 240px;
        padding: 40px;
        /* margin-left: 40%; */
        background-color: #fff;
        box-shadow: #112138 2px 0px 20px 0px;
        border-radius: 10px;
        :deep(.el-tabs__item.is-active) {
            background-color: #fff;
        }
        .UKEY {
            display: flex;
            justify-content: flex-end;
            margin: 5px 0;
        }
        .other {
            display: flex;
            justify-content: center;
            align-content: center;
            > img {
                width: 100%;
            }
        }
        .butt {
            margin-top: 5px;
            margin-bottom: 10px;
            text-align: center;
        }
    }
    .divider {
        font-size: 10px;
        color: #bdbec0;
    }
    .qrcode-container {
        display: flex;
        justify-content: center;
        width: 100%;
        > img {
            width: 180px;
            height: 190px;
        }
    }
    .el-form-item {
        margin-bottom: 5px;
    }
}
</style>
